import { config } from "dotenv";
import { z } from "zod";
import path from "path";
import { fileURLToPath } from "url";

// Load environment variables from .env file in project root
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const projectRoot = path.resolve(__dirname, "../..");
config({ path: path.join(projectRoot, ".env") });

// Environment configuration schema
const envSchema = z.object({
  // Embedding Provider
  EMBEDDER_PROVIDER: z.enum(["openai", "ollama", "openai-compatible", "gemini", "mistral"]).default("openai"),
  
  // OpenAI Configuration
  OPENAI_API_KEY: z.string().optional(),
  OPENAI_MODEL_ID: z.string().default("text-embedding-3-small"),

  // DashScope Configuration
  DASHSCOPE_API_KEY: z.string().optional(),

  // SiliconFlow Configuration
  SILICONFLOW_API_KEY: z.string().optional(),
  
  // Ollama Configuration
  OLLAMA_BASE_URL: z.string().default("http://localhost:11434"),
  OLLAMA_MODEL_ID: z.string().default("dengcao/Qwen3-Embedding-8B:Q5_K_M"),
  
  // OpenAI Compatible Configuration
  OPENAI_COMPATIBLE_BASE_URL: z.string().optional(),
  OPENAI_COMPATIBLE_API_KEY: z.string().optional(),
  OPENAI_COMPATIBLE_MODEL_ID: z.string().default("text-embedding-ada-002"),
  
  // Gemini Configuration
  GEMINI_API_KEY: z.string().optional(),
  GEMINI_MODEL_ID: z.string().default("models/text-embedding-004"),
  
  // Mistral Configuration
  MISTRAL_API_KEY: z.string().optional(),
  MISTRAL_MODEL_ID: z.string().default("mistral-embed"),
  
  // Vector Database Configuration
  QDRANT_URL: z.string().default("http://localhost:6333"),
  QDRANT_API_KEY: z.string().optional(),
  
  // Search Configuration
  DEFAULT_SEARCH_MIN_SCORE: z.string().transform(Number).pipe(z.number().min(0).max(1)).default("0.7"),
  DEFAULT_MAX_SEARCH_RESULTS: z.string().transform(Number).pipe(z.number().positive()).default("20"),
  
  // Vector Configuration
  VECTOR_DIMENSION: z.string().transform(Number).pipe(z.number().positive()).optional(), // Fallback
  VECTOR_DIMENSION_CODE: z.string().transform(Number).pipe(z.number().positive()).default("4096"),
  VECTOR_DIMENSION_TEXT: z.string().transform(Number).pipe(z.number().positive()).default("1024"),
  
  // Processing Configuration
  MAX_FILE_SIZE_BYTES: z.string().transform(Number).pipe(z.number().positive()).default("1048576"),
  BATCH_SEGMENT_THRESHOLD: z.string().transform(Number).pipe(z.number().positive()).default("60"),
  PARSING_CONCURRENCY: z.string().transform(Number).pipe(z.number().positive()).default("10"),
  CHUNK_SIZE: z.string().transform(Number).pipe(z.number().positive()).default("512"),
  CHUNK_OVERLAP: z.string().transform(Number).pipe(z.number().positive()).default("50"),
});

export type EnvConfig = z.infer<typeof envSchema>;

// Parse and validate environment configuration
export const envConfig = envSchema.parse(process.env);

// Configuration validation functions
export function validateEmbedderConfig(): { valid: boolean; error?: string } {
  switch (envConfig.EMBEDDER_PROVIDER) {
    case "openai":
      if (!envConfig.OPENAI_API_KEY) {
        return { valid: false, error: "OPENAI_API_KEY is required when using OpenAI embedder" };
      }
      break;
    case "ollama":
      if (!envConfig.OLLAMA_BASE_URL) {
        return { valid: false, error: "OLLAMA_BASE_URL is required when using Ollama embedder" };
      }
      break;
    case "openai-compatible":
      if (!envConfig.OPENAI_COMPATIBLE_BASE_URL || !envConfig.OPENAI_COMPATIBLE_API_KEY) {
        return { 
          valid: false, 
          error: "OPENAI_COMPATIBLE_BASE_URL and OPENAI_COMPATIBLE_API_KEY are required when using OpenAI-compatible embedder" 
        };
      }
      break;
    case "gemini":
      if (!envConfig.GEMINI_API_KEY) {
        return { valid: false, error: "GEMINI_API_KEY is required when using Gemini embedder" };
      }
      break;
    case "mistral":
      if (!envConfig.MISTRAL_API_KEY) {
        return { valid: false, error: "MISTRAL_API_KEY is required when using Mistral embedder" };
      }
      break;
  }
  
  return { valid: true };
}

export function getEmbedderConfig() {
  const provider = envConfig.EMBEDDER_PROVIDER;
  
  switch (provider) {
    case "openai":
      return {
        provider,
        options: {
          apiKey: envConfig.OPENAI_API_KEY,
          modelId: envConfig.OPENAI_MODEL_ID,
        }
      };
    case "ollama":
      return {
        provider,
        options: {
          baseUrl: envConfig.OLLAMA_BASE_URL,
          modelId: envConfig.OLLAMA_MODEL_ID,
        }
      };
    case "openai-compatible":
      return {
        provider,
        options: {
          baseUrl: envConfig.OPENAI_COMPATIBLE_BASE_URL,
          apiKey: envConfig.OPENAI_COMPATIBLE_API_KEY,
          modelId: envConfig.OPENAI_COMPATIBLE_MODEL_ID,
        }
      };
    case "gemini":
      return {
        provider,
        options: {
          apiKey: envConfig.GEMINI_API_KEY,
          modelId: envConfig.GEMINI_MODEL_ID,
        }
      };
    case "mistral":
      return {
        provider,
        options: {
          apiKey: envConfig.MISTRAL_API_KEY,
          modelId: envConfig.MISTRAL_MODEL_ID,
        }
      };
  }
}

export function getVectorStoreConfig() {
  return {
    url: envConfig.QDRANT_URL,
    apiKey: envConfig.QDRANT_API_KEY,
  };
}
